package com.pencilisland.pay.mgt.app.aspect;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pencilisland.pay.mgt.app.entity.TenantEntity;
import com.pencilisland.pay.mgt.app.service.TenantService;
import com.pencilisland.pay.mgt.console.entity.SysOrg;
import com.pencilisland.pay.mgt.console.entity.SysUser;
import com.pencilisland.pay.mgt.console.repository.UserRepository;
import com.pencilisland.pay.mgt.console.service.OrgService;
import com.pencilisland.pay.mgt.util.G;

/**
 * 同步商户信息
 * 
 * @author Breeze
 *
 */
@Aspect
@Component
public class TenantAspect {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	UserRepository userRepo;
	@Autowired
	TenantService tenantService;
	@Autowired
	OrgService orgService;

	@AfterReturning(pointcut = "execution(* com.pencilisland.pay.mgt.app.service.TenantService.save(..))")
	public void SyncSaveTenant(JoinPoint jp) {
		log.info("同步商户信息到系统用户表");
		TenantEntity tenant = (TenantEntity) jp.getArgs()[0];

		SysUser user = null;
		if (tenant.getUserId() != null) {
			user = userRepo.findOne(tenant.getUserId());
			user.setUserName(tenant.getName());
			userRepo.save(user);
		} else {
			user = new SysUser();
			user.setUserName(tenant.getName());
			user.setUserNumber(tenant.getCode());
			user.setStatus("0");
			user.setPassword(new Md5Hash("888888").toBase64());
			user.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
			user.setLoginName(G.str(tenantService.gen()));

			SysOrg org = orgService.findByOrgNumber("commercial_tenant");
			if (org != null)
				user.setOrgId(org.getOrgId());
			
			
			List<SysOrg> orgList = orgService.findAllParentOrg(user);
			if(orgList!=null&&!orgList.isEmpty()){
				StringBuilder orgIds = new StringBuilder();
				StringBuilder orgNames = new StringBuilder();
				for(int i=orgList.size()-1;i>=0;i--){
					SysOrg orgTemp = orgList.get(i);
					if("root".equals(orgTemp.getOrgCode())){
						continue;
					}
					
					if(orgIds.length()==0){
						orgIds.append(orgTemp.getOrgId());
						orgNames.append(orgTemp.getOrgName());
					}else{
						orgIds.append("/").append(orgTemp.getOrgId());
						orgNames.append("/").append(orgTemp.getOrgName());
					}
				}
				
				user.setOrgIdPath(orgIds.toString());
				user.setOrgNamePath(orgNames.toString());
			}

			userRepo.save(user);
			
			tenant.setUserId(user.getUserId());
			tenant.setLoginName(user.getLoginName());
			tenantService.save(tenant);
		}
	}

	@Pointcut("execution(* com.pencilisland.pay.mgt.app.service.TenantService.delete(..))")
	public void deleteTenant() {
	}

	@Before("deleteTenant()")
	public void SyncDeleteOrg(JoinPoint jp) {
		log.info("同步商户删除");
		Long id = G.l(jp.getArgs()[0]);
		TenantEntity tenant = tenantService.loadData(id);
		userRepo.delete(tenant.getUserId());

	}
	
}
